//
//  KHBodyFatBlueToothHelper.m
//  KissHealth
//
//  Created by bingo on 2019/1/15.
//  Copyright © 2019 Mark. All rights reserved.
//

#import "KHBodyFatBlueToothHelper.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "KHBlueToothHelper.h"

@interface KHBodyFatBlueToothHelper ()<CBCentralManagerDelegate,CBPeripheralDelegate>

@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, strong) NSTimer *timer;       //连接超时


@property (nonatomic, strong) CBUUID *readUUID;
@property (nonatomic, strong) CBUUID *writeUUID;
@property (nonatomic, strong) CBUUID *notificationUUID;
@property (nonatomic, strong) CBUUID *serviceUUID;

@end

@implementation KHBodyFatBlueToothHelper {
    int countDown;  //倒计时
}

- (void)scan {
    [self initDevice];
}

- (void)initDevice{
    NSLog(@"initDevice");
    countDown = 0;
    if (!_centralManager) {
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
    }
}

#pragma mark - CBCentralManagerDelegate

// 在 cetral 的状态变为 CBManagerStatePoweredOn 的时候开始扫描
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    if (central.state == CBManagerStatePoweredOn) {
        // 扫描指定服务的设备
        CBUUID *serviceUUID = [CBUUID UUIDWithString:kBodyFatServiceUUID];
        [_centralManager scanForPeripheralsWithServices:@[serviceUUID]
                                            options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }];
    } else {
        [KHBlueToothHelper showOpenBlueToothAlert];
    }
}

// 扫描到设备
- (void)centralManager:(CBCentralManager *)central
 didDiscoverPeripheral:(CBPeripheral *)peripheral
     advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI {
    
    if (!peripheral.name) return; // Ingore name is nil peripheral.
    NSLog(@"扫描到的设备名称: %@", peripheral.name);
    self.peripheral = peripheral;
    peripheral.delegate = self;
    // 连接设备
    [_centralManager connectPeripheral:self.peripheral options:nil];
}

// 设备连接成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@"设备连接成功");
    
    [peripheral discoverServices:@[self.serviceUUID]];
}

// 设备连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"Failed to connnet peripheral %@ (%@)", peripheral, error);
 
}

// 设备断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error{
    NSLog(@"设备断开连接");
}


#pragma mark - CBPeripheralDelegate
// 发现服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    if (error) {
        NSLog(@"没有发现服务");
        return;
    }
    
    for (CBService *service in peripheral.services) {
        if ([service.UUID isEqual:self.serviceUUID]) {
            // 触发发现特征
            [self.peripheral discoverCharacteristics:@[self.writeUUID, self.readUUID, self.notificationUUID] forService:service];
        }
    }
}

// 发现特征
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(nonnull CBService *)service error:(nullable NSError *)error {
    if (error) {
        return;
    }
    
    if ([service.UUID isEqual:self.serviceUUID]) {
        for (CBCharacteristic *characteristic in service.characteristics) {
            if ([characteristic.UUID isEqual:self.writeUUID]) {
                /**
                 // 向设备写入个人参数设置,为了接收到完整的体脂数据
                 byte[] data = new byte[]{(byte) 0xFD, 0x53, 0x00, 0x00, 0x40, (byte) 0x9F, (byte) 0xA7};
                 */
                Byte dataValue[7] = {0};
                dataValue[0] = 0xFD; dataValue[1] = 0x53; dataValue[2] = 0x00;
                dataValue[3] = 0x00; dataValue[4] = 0x40; dataValue[5] = 0x9F;
                dataValue[6] = 0xA7;
                NSData *data = [NSData dataWithBytes:&dataValue length:sizeof(dataValue)];
    
                // 写入特征值
                [self.peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
            } else if ([characteristic.UUID isEqual:self.notificationUUID]) {
                // 订阅通知特征
                [self.peripheral setNotifyValue:YES forCharacteristic:characteristic];
            } else if ([characteristic.UUID isEqual:self.readUUID]) {
                // 读取特征值
                [peripheral readValueForCharacteristic:characteristic];
            }
            
            // 搜索特征的描述
            [peripheral discoverDescriptorsForCharacteristic:characteristic];
        }
    }
}


// 读取特征值/写入成功后的应答
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"update value error: %@", error);
    } else {
        NSData *responseData = characteristic.value;
        NSLog(@"responseData:%@", responseData);
    }
}

// 写入成功
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error {
    if (!error) {
        NSLog(@"Write Success");
    } else {
        NSLog(@"WriteVale Error = %@", error);
    }
}



// 发现描述
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    
    for (CBDescriptor *descriptor in characteristic.descriptors) {
        [peripheral readValueForDescriptor:descriptor];
    }
    
}

// 读取描述
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error {
    NSLog(@"ValueForDescriptor:%@", descriptor.value);
}

#pragma mark - getters
- (CBUUID *)serviceUUID {
    if (!_serviceUUID) {
        _serviceUUID = [CBUUID UUIDWithString:kBodyFatServiceUUID];
    }
    return _serviceUUID;
}

- (CBUUID *)writeUUID {
    if (!_writeUUID) {
        _writeUUID = [CBUUID UUIDWithString:kBodyFatWriteCharacteristicUUID];
    }
    return _writeUUID;
}

- (CBUUID *)readUUID {
    if (!_readUUID) {
        _readUUID = [CBUUID UUIDWithString:kBodyFatReadCharacteristicUUID];
    }
    return _readUUID;
}

- (CBUUID *)notificationUUID {
    if (!_notificationUUID) {
        _notificationUUID = [CBUUID UUIDWithString:kBodyFatNotificationUUID];
    }
    return _notificationUUID;
}

@end
